package com.xuyu.controller;

import com.google.code.kaptcha.Producer;
import com.xuyu.entity.CurrentUser;
import com.xuyu.entity.LoginUser;
import com.xuyu.entity.Result;
import com.xuyu.entity.User;
import com.xuyu.service.UserService;
import com.xuyu.utils.DigestUtil;
import com.xuyu.utils.TokenUtils;
import com.xuyu.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    //注入DefaultKaptcha的bean对象--生成验证码图片的
    @Resource(name = "captchaProducer")
    private Producer producer;

    //注入redis模板
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    private UserService userService;
    //生成验证码图片的url接口
    @RequestMapping("/captcha/captchaImage")
    public void captChaImage(HttpServletResponse response){

        ServletOutputStream out = null;
        try {
            //生成验证码图片的文件
            String text = producer.createText();

            //使用验证码文本生成验证码图片 ---BufferedImage对象就代表生成的验证码图片， --在内存中
            BufferedImage image = producer.createImage(text);
            //将验证码存入内存redis中  操作器  设置键的时间30分钟
            stringRedisTemplate.opsForValue().set(text,"",60*30, TimeUnit.SECONDS);
            /**
             * 将验证码图片相应给前端：
             */
            //设置相应正文 image/jpeg
            response.setContentType("image/jpeg");
            //i将验证码图片写给前端
            out = response.getOutputStream();
            ImageIO.write(image,"jpg",out); //使用响应对象的字节输出流写入验证码图片，自己就给前端写入了
            //刷新
            out.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭字节输出流
            try {
                if(out != null){
                    out.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
// 登录的url接口/login

    @Autowired
    private TokenUtils tokenUtils;
    /**
     * @RequestBody 表示接收并封装前端传递的登录的用户信息的json数据
     * @param loginUser
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){
        //拿到客户录入的验证码
        String code=loginUser.getVerificationCode();
       if (!stringRedisTemplate.hasKey(code)){
           return Result.err(Result.CODE_ERR_BUSINESS,"验证码错误！");
       }


        //根据账号，判断账号是否存在
        User userByCode = userService.findUserByCode(loginUser.getUserCode());
        //如果账号不存在，则返回错误信息
        if (userByCode != null)//账号存在
        {
            //判断用户是否被审核了
            if (userByCode.getUserState().equals(WarehouseConstants.USER_STATE_PASS)){
                //拿到录入的密码
                String userPwd = loginUser.getUserPwd();
                //进行md5加密
                userPwd = DigestUtil.hmacSign(userPwd);
                if (userPwd.equals(userByCode.getUserPwd())){
                    //密码正确
                    //token  生成jwt token并存储到redis中
                    CurrentUser currentUser =
                            new CurrentUser(userByCode.getUserId(),userByCode.getUserCode(),userByCode.getUserName());
                    String token = tokenUtils.loginSign(currentUser, userPwd);//放入加密过的密钥
//向客户端相应jwt token
                    return Result.ok("登录成功！",token);
                }else {
                    return Result.err(Result.CODE_ERR_BUSINESS,"密码错误！");
                }

            }else{//用户未审核

                return Result.err(Result.CODE_ERR_BUSINESS,"账号未审核！");

            }

        }else {//账号不存在

            return Result.err(Result.CODE_ERR_BUSINESS,"账号不存在！");
        }


    }






}
